
package com.be.beadmin.material.impl;

import cn.hutool.core.util.ObjectUtil;
import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.common.entity.SortExpressEntity;
import com.be.beadmin.common.exception.BeadminException;
import com.be.beadmin.common.utils.JpaQueryBuilder;
import com.be.beadmin.common.utils.JpaQueryBuilderNew;
import com.be.beadmin.common.utils.JpaSortBuilder;
import com.be.beadmin.material.dto.input.PurchaseOrderDetailDto;
import com.be.beadmin.material.dto.output.PurchaseOrderDetailEx;
import com.be.beadmin.material.dto.output.PurchaseOrderTotalEx;
import com.be.beadmin.material.entity.PurchaseOrder;
import com.be.beadmin.material.entity.PurchaseOrderDetail;
import com.be.beadmin.material.entity.PurchaseOrderDetail_;
import com.be.beadmin.material.entity.PurchaseOrderTotal;
import com.be.beadmin.material.mapper.PurchaseOrderDetailMapper;
import com.be.beadmin.material.mapper.PurchaseOrderDetailMapperEx;
import com.be.beadmin.material.mapper.PurchaseOrderTotalMapper;
import com.be.beadmin.material.mapper.PurchaseOrderTotalMapperEx;
import com.be.beadmin.material.repository.PurchaseOrderDetailRepository;
import com.be.beadmin.material.repository.PurchaseOrderRepository;
import com.be.beadmin.material.service.PurchaseOrderDetailService;
import com.be.beadmin.material.util.JpaQueryBuilderJoin;
import com.be.beadmin.material.util.JpaSortBuilderJoin;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;
import javax.swing.plaf.basic.BasicInternalFrameTitlePane;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* @description 服务实现
* @author zmy
* @date 2023-05-14
**/
@Service
@RequiredArgsConstructor
public class PurchaseOrderDetailServiceImpl implements PurchaseOrderDetailService {

    @Autowired
    private PurchaseOrderDetailRepository purchaseOrderDetailRepository;
    @Autowired
    private PurchaseOrderDetailMapper purchaseOrderDetailMapper;
    @Autowired
    private PurchaseOrderDetailMapperEx purchaseOrderDetailExMapper;

    @Autowired
    private PurchaseOrderRepository purchaseOrderRepository;

    @Autowired
    private PurchaseOrderTotalMapperEx purchaseOrderTotalMapperEx;

    @Override
    public Page<PurchaseOrderDetailEx> getPurchaseOrderDetailByPage(PageEntity pageEntity) {
            Pageable pageable = PageRequest.of(
            pageEntity.getCurrent() -1,
            pageEntity.getPageSize());
            Page<PurchaseOrderDetail> page = purchaseOrderDetailRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 =   JpaQueryBuilder.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(PurchaseOrderDetail_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if(pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(PurchaseOrderDetail_.createTime).as(Date.class)));
                    }
                    return  criteriaBuilder.and(list.toArray(p));
                    }
                    , pageable);
            Page<PurchaseOrderDetailEx> page1 = page.map(purchaseOrderDetailExMapper::toEntity);
            return page1;

    }

    @Override
    public Page<PurchaseOrderTotalEx> getPurchaseOrderTotalByPage(PageEntity pageEntity) {
        Pageable pageable = PageRequest.of(
                pageEntity.getCurrent() -1,
                pageEntity.getPageSize());
        Page<PurchaseOrderDetail> page = purchaseOrderDetailRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    Join<PurchaseOrderDetail,PurchaseOrder> join=root.join("purchaseOrder",JoinType.LEFT);
                    List<Predicate> list = new ArrayList<>();
                    //JpaQueryBuilderJoin继承自JpaQueryBuilder
                    Predicate pre1 =   JpaQueryBuilderJoin.getPredicateJoin(join, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(PurchaseOrderDetail_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();//只排序了order里的属性
                    if(pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilderJoin.getPredicateJoin(join, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(PurchaseOrderDetail_.createTime).as(Date.class)));
                    }
                    return  criteriaBuilder.and(list.toArray(p));
                }
                , pageable);
        Page<PurchaseOrderTotal> page2=page.map(entity->{
            PurchaseOrderTotal purchaseOrderTotal=new PurchaseOrderTotal();
           PurchaseOrder purchaseOrder=purchaseOrderRepository.findPurchaseOrderByPo(entity.getPo());
           //复制属性
           BeanUtils.copyProperties(entity,purchaseOrderTotal);
           //purchaseOrderTotal.setId(purchaseOrder.getId());
           BeanUtils.copyProperties(purchaseOrder,purchaseOrderTotal);
           //purchaseOrderTotal.setPoItem(entity.getPoItem());
           return purchaseOrderTotal;
        });
        Page<PurchaseOrderTotalEx> page3=page2.map(purchaseOrderTotalMapperEx::toEntity);
        return page3;
    }

    @Override
    public void addPurchaseOrderDetail(PurchaseOrderDetailDto purchaseOrderDetailDto) {
            PurchaseOrderDetail result = purchaseOrderDetailRepository.findPurchaseOrderDetailByIdAndDelete(purchaseOrderDetailDto.getId(), 0);
            if(ObjectUtil.isNotEmpty(result)) {
                throw new BeadminException("PurchaseOrderDetail不存在,请重新查询");
            }
            PurchaseOrderDetail purchaseOrderDetail = purchaseOrderDetailMapper.toEntity(purchaseOrderDetailDto);
            purchaseOrderDetailRepository.save(purchaseOrderDetail);
    }

    @Override
    public void updatePurchaseOrderDetail(PurchaseOrderDetailDto purchaseOrderDetailDto) {
            PurchaseOrderDetail purchaseOrderDetail = purchaseOrderDetailRepository.findPurchaseOrderDetailById(purchaseOrderDetailDto.getId());
            purchaseOrderDetail = purchaseOrderDetailMapper.toEntity(purchaseOrderDetailDto);
            purchaseOrderDetailRepository.save(purchaseOrderDetail);
    }


    @Override
    public void delPurchaseOrderDetail(String id) {
        PurchaseOrderDetail purchaseOrderDetail = purchaseOrderDetailRepository.findPurchaseOrderDetailById(id);
        purchaseOrderDetail.setDelete(1);
        purchaseOrderDetailRepository.save(purchaseOrderDetail);
    }

    @Override
    public void delPurchaseOrderDetails (List<String> ids) { }
    public void setMaterialNum(String id, int num) {
        PurchaseOrderDetail pOD = purchaseOrderDetailRepository.findPurchaseOrderDetailByIdAndDelete(id, 0);

        int x = pOD.getUndeliveredQty() - num;
        if (x <= 0) {
            //该种物料全部到货
            pOD.setUndeliveredQty(0);
            pOD.setIsFinished("Y");
        } else {
            pOD.setUndeliveredQty(x);
        }
        purchaseOrderDetailRepository.save(pOD);
//        //判断是否全部分料
//        String poId = pOD.getPoIdentification();
//        List<PurchaseOrderDetail> listDetail = purchaseOrderDetailRepository.findPurchaseOrderDetailsByPoIdentificationAndDelete(poId, 0);
//        boolean isAllFinished = false;
//        for (PurchaseOrderDetail p : listDetail) {
//            if (p.getIsFinished() != "Y") {
//                isAllFinished = false;
//                break;
//            } else {
//                isAllFinished = true;
//            }
//        }
//        if (isAllFinished) {
//            PurchaseOrder purchaseOrder = purchaseOrderRepository.findPurchaseOrderByIdAndDelete(poId, 0);
//            purchaseOrder.setIsClosed("Y");
//            purchaseOrderRepository.save(purchaseOrder);
//        }
    }
}